#include "emulator.h"
#include <QFile>
#include <QDebug>

Emulator::Emulator(QObject *parent) : QObject(parent)
{
    console = agnes_make();
}

Emulator::~Emulator(void)
{
    agnes_destroy(console);
}

bool Emulator::load(QString& romfile)
{
    QFile rom(romfile);
    if (!rom.open(QIODevice::ReadOnly))
    {
        return false;
    }

    game = rom.readAll();

    rom.close();

    return agnes_load_ines_data(console, game.data(), game.size());
}

void Emulator::step(QImage& frame, agnes_input_t* player1, agnes_input_t* player2)
{
    agnes_set_input(console, player1, player2);
    agnes_next_frame(console);

    for (int y = 0; y < AGNES_SCREEN_HEIGHT; y++) {
        for (int x = 0; x < AGNES_SCREEN_WIDTH; x++) {
            agnes_color_t c = agnes_get_screen_pixel(console, x, y);
            frame.setPixel(x, y, QColor(c.r, c.g, c.b).rgb());
        }
    }
}
